package com.example.myaku.network;

//扫描IP，目前默认扫描24位掩码IP

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.NetworkInterface;
import java.net.Inet4Address;
import java.util.Enumeration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class SeaAKU {

    private static final int PORT = 80;
    private static final int TIMEOUT = 1500; // ms
    private static final String TAG = "SeaAKU";

    private static ExecutorService executor = Executors.newFixedThreadPool(20);
    private Handler mainHandler = new Handler(Looper.getMainLooper());
    private OnDeviceFoundListener listener;
    private boolean isStopped = false;
    private static volatile SeaAKU instance;
    private boolean isScanning = false;

    private OnScanCompleteListener scanCompleteListener;
    private int totalScanTasks = 0;
    private AtomicInteger completedScanTasks = new AtomicInteger(0);

    private SeaAKU(Context context) {
    }

    public static SeaAKU getInstance(Context context) {
        if (instance == null) {
            synchronized (SeaAKU.class) {
                if (instance == null) {
                    instance = new SeaAKU(context.getApplicationContext());
                }
            }
        }
        return instance;
    }

    public interface OnDeviceFoundListener {
        void onDeviceFound(String ip);
    }
// 扫描完成监听
    public interface OnScanCompleteListener {
        void onScanComplete();
    }
    public void setOnScanCompleteListener(OnScanCompleteListener listener) {
        this.scanCompleteListener = listener;
    }
    private void notifyTaskCompleted() {
        int count = completedScanTasks.incrementAndGet();
        if (count == totalScanTasks && scanCompleteListener != null) {
            mainHandler.post(scanCompleteListener::onScanComplete);
        }
    }


    public void setOnDeviceFoundListener(OnDeviceFoundListener listener) {
        this.listener = listener;
    }

    public void startScanIfNotStarted(Context context) {
        if (!isScanning) {
            startScan(context);
            isScanning = true;
        }
    }
    public void startScan(Context context) {
        String subnet = getLocalSubnet(context);
        if (isStopped) {
            executor = Executors.newFixedThreadPool(20); // 可根据需要调整线程池大小
            isStopped = false;
        }
        if (subnet == null) {
            Log.e(TAG, "无法获取本地子网");
            return;
        }
        completedScanTasks.set(0);
        totalScanTasks = 254; // 总共扫描的 IP 数量

        for (int i = 1; i <= 254; i++) {
            String ip = subnet + "." + i;
            if (!ip.equals(getLocalIpAddress(context))) { // 跳过本机
                scanIp(ip);
            } else {
                notifyTaskCompleted();
            }
        }
    }

    private void scanIp(String ip) {
        executor.execute(() -> {
            try (Socket socket = new Socket()) {
                socket.connect(new java.net.InetSocketAddress(ip, PORT), TIMEOUT);
                onPortOpen(ip);
            } catch (IOException ignored) {
                // 忽略连接失败
            } finally {
                notifyTaskCompleted();
            }
        });
    }


    private void onPortOpen(String ip) {
        mainHandler.post(() -> {
            Log.d(TAG, "发现开放 80 端口的设备: " + ip);
            if (listener != null) {
                listener.onDeviceFound(ip);
            }
        });
    }

    public void stopScan() {
        isStopped = true;
        executor.shutdownNow();
    }

    // 获取本机 IPv4 地址并提取子网段（如 192.168.1）
    private String getLocalSubnet(Context context) {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (!address.isLoopbackAddress() && address instanceof Inet4Address) {
                        String ip = address.getHostAddress();
                        String[] parts = ip.split("\\.");
                        if (parts.length == 4) {
                            return parts[0] + "." + parts[1] + "." + parts[2];
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "获取本地子网失败", e);
        }
        return null;
    }

    // 获取本机 IP 地址
    private String getLocalIpAddress(Context context) {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (!address.isLoopbackAddress() && address instanceof Inet4Address) {
                        return address.getHostAddress();
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "获取本机 IP 失败", e);
        }
        return null;
    }
}
